package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.config.Config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * 预警布控-人脸图片接口
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "预警布控-人脸图片接口",description="WarningfacePicController")
@RestController
@RequestMapping("/warning/facePic")
public class WarningfacePicController extends BaseController
{
    @ApiOperation("查询预警布控-人脸图片")
    @GetMapping("/")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String select(@RequestParam Map<String, String> data) throws IOException {
        if(data!=null&&data.size()>0)
        {
            String host = (String)data.get("host");
            String query =  Config.buildMap(data);
            HttpMethod method = HttpMethod.GET;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            String lib = Config.client(Config.getStarturlpre(host)+"/warning/facelib/?"+query,method,null,headers);
            JSONObject getlibresult = JSONObject.parseObject(lib);
            JSONObject resultData = getlibresult.getJSONObject("Data");
            if(resultData!=null){
                JSONArray libs = resultData.getJSONArray("FaceLibInfo");
                if(libs!=null&&libs.size()>0){
                    StringBuilder libId = new StringBuilder();
                    for(int i=0;i<libs.size();i++){
                        if(i==libs.size()-1){
                            libId.append(libs.getJSONObject(i).getIntValue("Id"));
                        }else{
                            libId.append(libs.getJSONObject(i).getIntValue("Id")).append(",");
                        }
                    }
                    query = query + "facelibid="+libId.toString();
                }
            }
            logger.error("select on  warning/facePic query===" + query);
            String analyseResults = Config.client(Config.getStarturlpre(host)+"/warning/facePic/?"+query,method,null,headers);
            logger.error("select on  warning/facePic analyseResults===" + analyseResults);
            LogController.add("/warning/facePic/",LogController.METHOD_GET,1);
            JSONObject result = JSONObject.parseObject(analyseResults);
            JSONObject jsonObject = result.getJSONObject("Data");
            if(jsonObject!=null){
                JSONArray array = jsonObject.getJSONArray("FacePicDesc");
                if(array!=null&&array.size()>0){
                    for(int i =0;i<array.size();i++){
                        int id = array.getJSONObject(i).getIntValue("Id");
                        String path = savePic(host,id);
                        array.getJSONObject(i).put("Path",path);
                    }
                }
            }
            return result.toJSONString();
        }
        LogController.add("/warning/facePic/",LogController.METHOD_GET,0);
        return "{}";
    }
    @ApiOperation("修改预警布控-人脸图片")
    @PutMapping("/")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String change(@RequestParam Map<String, String> data) throws Exception {
        if(data!=null&&data.size()>0)
        {
            String host = data.get("host");
            String disUrl="/warning/facePic/?"+Config.buildMap(data);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            if(isExist(data.get("path"))&&isExist(data.get("fileName"))){
                FileSystemResource resource = new FileSystemResource((Config.createFile(data.get("path"),data.get("fileName"))));
                param.add("file", resource);
            }
            HttpMethod method=HttpMethod.PUT;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            String response = Config.clientWithFormData(Config.getStarturlpre(host)+disUrl,method,param,headers);
            LogController.add("/warning/facePic/",LogController.METHOD_PUT,1);
            return response;
        }
        LogController.add("/warning/facePic/",LogController.METHOD_PUT,0);
        return "{}";
    }

    @ApiOperation("新增预警布控-人脸图片")
    @PostMapping("/")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String update(@RequestParam Map<String, String> data) throws Exception {
        if(data!=null&&data.size()>0)
        {
            String host = data.get("host");
            String disUrl="/warning/facePic/?"+Config.buildMap(data);
            FileSystemResource resource = new FileSystemResource((Config.createFile(data.get("path"),data.get("fileName"))));
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            HttpMethod method=HttpMethod.POST;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            long now = System.currentTimeMillis();
            String query = "name="+now+"&reason="+now+"&stranger=false";
            String lib = Config.client(Config.getStarturlpre(host)+"/warning/facelib/?"+query,method,null,headers);
            JSONObject getlibresult = JSONObject.parseObject(lib);
            int libId = getlibresult.getIntValue("Data");
            disUrl = disUrl + "libid="+libId;
            String response = Config.clientWithFormData(Config.getStarturlpre(host)+disUrl,method,param,headers);
            LogController.add("/warning/facePic/",LogController.METHOD_POST,1);
            return response;
        }
        LogController.add("/warning/facePic/",LogController.METHOD_POST,0);
        return "{}";
    }

    @ApiOperation("通过id删除预警布控-人脸图片")
    @DeleteMapping("/")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String iddelete(@RequestParam Map<String, String> data)
    {
        if(data!=null&&data.size()>0)
        {
            String host = (String)data.get("host");
            String query =  Config.buildMap(data);
            HttpMethod method = HttpMethod.DELETE;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            logger.error("iddelete on  warning/facePic query===" + query);
            String analyseResults = Config.client(Config.getStarturlpre(host)+"/warning/facePic/?"+query,method,null,headers);
            logger.error("iddelete on  warning/facePic analyseResults===" + analyseResults);
            LogController.add("/warning/facePic/",LogController.METHOD_DELETE,1);
            String libid = data.get("libid");
            Config.client(Config.getStarturlpre(host)+"/warning/facelib/?id="+libid,method,null,headers);
            return analyseResults;
        }
        LogController.add("/warning/facePic/",LogController.METHOD_DELETE,0);
        return "{}";
    }

    @ApiOperation("查询指定ID预警布控-人脸图片")
    @GetMapping("/byid")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String idselect(@RequestParam Map<String, String> data) throws IOException {
        if(data!=null&&data.size()>0)
        {
            String host = (String)data.get("host");
            String query =  Config.buildMap(data);
            HttpMethod method = HttpMethod.GET;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            logger.error("idselect on  warning/facePic query===" + query);
            String analyseResults = Config.client(Config.getStarturlpre(host)+"/warning/facePic/?"+query,method,null,headers);
            logger.error("idselect on  warning/facePic analyseResults===" + analyseResults);
            LogController.add("/warning/facePic/byid",LogController.METHOD_GET,1);
            JSONObject result = JSONObject.parseObject(analyseResults);
            JSONObject jsonObject = result.getJSONObject("Data");
            if(jsonObject!=null){
                JSONArray array = jsonObject.getJSONArray("FacePicDesc");
                if(array!=null&&array.size()>0){
                    for(int i =0;i<array.size();i++){
                        int id = array.getJSONObject(i).getIntValue("Id");
                        String path = savePic(host,id);
                        array.getJSONObject(i).put("Path",path);
                    }
                }
            }
            return result.toJSONString();
        }
        LogController.add("/warning/facePic/byid",LogController.METHOD_GET,0);
        return "{}";
    }

    @ApiOperation("获取指定ID预警布控图片-人脸图片")
    @GetMapping("/picture")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String idselectpic(@RequestParam Map<String, String> data)
    {
        if(data!=null&&data.size()>0)
        {
            String host = (String)data.get("host");
            String query =  Config.buildMap(data);
            HttpMethod method = HttpMethod.GET;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            logger.error("idselectpic on  warning/facePic query===" + query);
            String analyseResults = Config.client(Config.getStarturlpre(host)+"/warning/facePic/?"+query,method,null,headers);
            logger.error("idselectpic on  warning/facePic analyseResults===" + analyseResults);
            LogController.add("/warning/facePic/picture",LogController.METHOD_GET,1);
            return analyseResults;
        }
        LogController.add("/warning/facePic/picture",LogController.METHOD_GET,0);
        return "{}";
    }

    @ApiOperation("通过证件号删除预警布控-人脸图片")
    @DeleteMapping("/pid")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public String piddelete(@RequestParam Map<String, String> data)
    {
        if(data!=null&&data.size()>0)
        {
            String host = (String)data.get("host");
            String query =  Config.buildMap(data);
            HttpMethod method = HttpMethod.DELETE;
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", Config.getmCurtoken(host));
            logger.error("piddelete on  warning/facePic query===" + query);
            String analyseResults = Config.client(Config.getStarturlpre(host)+"/warning/facePic/?"+query,method,null,headers);
            logger.error("piddelete on  warning/facePic analyseResults===" + analyseResults);
            LogController.add("/warning/facePic/pid",LogController.METHOD_DELETE,1);
            return analyseResults;
        }
        LogController.add("/warning/facePic/pid",LogController.METHOD_DELETE,0);
        return "{}";
    }

    public boolean isExist(String value){
        return value != null && !value.equals("");
    }

    private String savePic(String host,int id) throws IOException {
        URL url = new URL(Config.getStarturlpre(host) +"/warning/facePic/picture?id="+id);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(15*1000);
        con.setReadTimeout(15*1000);
        con.addRequestProperty("X-Token",Config.getmCurtoken(host));
        InputStream is = con.getInputStream();
        byte[] bs = new byte[256*1024];
        int len;
        String fileName = "DEPLOY"+System.currentTimeMillis()+".jpg";
        String filePath = Config.getMimgpath()+fileName;
        OutputStream os = new FileOutputStream(filePath);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        is.close();
        return Config.getMurlpath()+fileName;
    }
}